<script setup lang="ts">
import type {
  PlusColumn,
  FieldValues,
  OptionsRow,
  PlusFormGroupRow,
  PlusDialogFormInstance
} from "plus-pro-components";
import { PlusDialogForm } from "plus-pro-components";
import { useColumns } from "./columns";
import {
  computed,
  Fragment,
  h,
  nextTick,
  onBeforeMount,
  onMounted,
  reactive,
  ref
} from "vue";
import { FlowerMaterial, FlowerOccasion, FlowerReceiver } from "@/constants";
import { getFlowerTypeOptions } from "@/api/flower";
import { ElUpload, ElImage } from "element-plus";
import { UPLOAD_IMAGE_URL } from "@/api/images";
import { ImageItem } from "types/image";
import { IconifyIconOnline } from "@/components/ReIcon";
import { getAppConfig, updateAppConfig } from "@/api/config";
import { SwiperConfigItem } from "types/app-config";
import { message } from "@/utils/message";
import { FlowerTypeOptionItem } from "types/flower";
import { cloneDeep } from "@pureadmin/utils";

const SERVER_URL = import.meta.env.VITE_SERVER_URL;

const state = reactive({
  loading: false,
  submitting: false
});

const dataList = ref<SwiperConfigItem[]>();

const flowerTypeOptions = ref<OptionsRow[]>([]);
const flowerTypeMap = ref<Record<number, FlowerTypeOptionItem>>([]);

const loadFlowerType = async () => {
  try {
    const response = await getFlowerTypeOptions();
    flowerTypeOptions.value = response.map(item => ({
      label: item.name,
      value: item.id
    }));
    flowerTypeMap.value = response.reduce((map, item) => {
      map[item.id] = item;
      return map;
    }, {});
  } catch (error) {
    console.log(error);
  }
};

const { columns } = useColumns({
  flowerTypeMap,
  onEdit: (row, index) => {
    itemIndex.value = index;
    formData.value = {
      id: row.id,
      image: row.image,
      size: row.size,
      receiver: row.receiver,
      material: row.material,
      occasion: row.occasion,
      type: row.type
    };
    formVisible.value = true;
  },
  onDelete: async (_, index) => {
    try {
      const data = cloneDeep(dataList.value);

      data.splice(index, 1);
      await updateAppConfig({
        name: "weixin-home-swiper",
        data: data
      });
      message("删除成功", { type: "success" });
      loadData();
    } catch (e) {
      if (e.response.data && e.response.data.message) {
        message(e.response.data.message, { type: "error" });
      } else {
        message("删除失败", { type: "error" });
      }
      console.log(e);
    }
  },
  onRowDrop: ({ newIndex, oldIndex }) => {
    const currentRow = dataList.value.splice(oldIndex, 1)[0];
    dataList.value.splice(newIndex, 0, currentRow);

    updateAppConfig({
      name: "weixin-home-swiper",
      data: dataList.value
    }).finally(() => {
      loadData();
    });
  }
});

const loadData = async () => {
  try {
    state.loading = true;
    const response = await getAppConfig("weixin-home-swiper");
    dataList.value = response.data;
    console.log(response);
    state.loading = false;
  } catch (error) {
    console.log(error);
  }
};

onMounted(async () => {
  await loadFlowerType();
  loadData();
});

const itemIndex = ref<number | null>(null);
const formRules = {
  image: [
    {
      required: true,
      message: "请上传图片"
    }
  ]
};
const formVisible = ref(false);
const formRef = ref<PlusDialogFormInstance | null>(null);
const formData = ref<FieldValues>({ status: 1 });
const formColumns: PlusFormGroupRow[] = [
  {
    title: "轮播图封面",
    cardProps: {
      shadow: "never"
    },
    columns: [
      {
        label: "图片",
        prop: "image",
        width: 100,
        valueType: "img",
        renderField(value: string, onChange) {
          return h(Fragment, [
            h(
              ElUpload,
              {
                action: UPLOAD_IMAGE_URL,
                listType: "picture-card",
                showFileList: false,
                onSuccess: async (data: ImageItem) => {
                  onChange(
                    `/static/images/${data.folder}/${data.hash}.${data.format}`
                  );
                  nextTick(() => {
                    formRef.value.formInstance.validateField(["image"]);
                  });
                },
                class: "swiper-upload"
              },
              () => {
                if (value) {
                  return h(ElImage, {
                    src: SERVER_URL + value,
                    fit: "cover",
                    style: "width:100%; height:100%"
                  });
                } else {
                  return h(IconifyIconOnline, { icon: "ep:plus" });
                }
              }
            )
          ]);
        }
      }
    ]
  },
  {
    title: "筛选条件",
    cardProps: {
      shadow: "never"
    },
    columns: [
      {
        label: "搜索关键词",
        prop: "kw",
        valueType: "input"
      },
      {
        label: "枝数",
        width: 120,
        prop: "size",
        valueType: "input-number",
        colProps: {
          span: 12
        }
      },
      {
        label: "对象",
        prop: "receiver",
        valueType: "select",
        options: FlowerReceiver,
        colProps: {
          span: 12
        }
      },
      {
        label: "花材",
        prop: "material",
        valueType: "select",
        options: FlowerMaterial,
        colProps: {
          span: 12
        }
      },
      {
        label: "场合",
        prop: "occasion",
        valueType: "select",
        options: FlowerOccasion,
        colProps: {
          span: 12
        }
      },
      {
        label: "分类",
        prop: "type",
        valueType: "select",
        options: computed(() => flowerTypeOptions.value),
        colProps: {
          span: 12
        }
      }
    ]
  }
];

const handleNew = () => {
  itemIndex.value = null;
  formData.value = {};
  formVisible.value = true;
};

const handleConfirm = async e => {
  try {
    state.submitting = true;

    if (itemIndex.value !== null) {
      const data = cloneDeep(dataList.value);

      data[itemIndex.value] = e;

      await updateAppConfig({
        name: "weixin-home-swiper",
        data
      });
    } else {
      await updateAppConfig({
        name: "weixin-home-swiper",
        data: [...dataList.value, e].map((item, index) => ({
          ...item,
          id: index + 1
        }))
      });
    }

    message("创建成功", { type: "success" });
    formVisible.value = false;
    loadData();
  } catch (e) {
    if (e.response.data && e.response.data.message) {
      message(e.response.data.message, { type: "error" });
    } else {
      message("创建失败", { type: "error" });
    }
    console.log(e);
  } finally {
    state.submitting = false;
  }
};
</script>

<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span>轮播图配置</span>

          <el-space>
            <el-button type="primary" @click="handleNew">
              <template #icon>
                <IconifyIconOnline icon="ep:plus" />
              </template>
              新增
            </el-button>
          </el-space>
        </div>
      </template>
      <pure-table
        border
        adaptive
        row-key="id"
        :loading="state.loading"
        :data="dataList"
        :columns="columns"
      />
    </el-card>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="formVisible"
      v-model="formData"
      :destroy-on-close="true"
      :title="itemIndex ? '修改' : '添加'"
      :form="{
        group: formColumns,
        rules: formRules,
        labelPosition: 'top',
        rowProps: {
          gutter: 12
        }
      }"
      :confirmLoading="state.submitting"
      @confirm="handleConfirm"
    />
  </div>
</template>
<style scoped lang="scss">
:deep(.swiper-upload) {
  .el-upload--picture-card {
    width: 320px;
    overflow: hidden;
  }
}
</style>
